import NProgress from "nprogress";

// 请求的封装
const BASE_URL = "http://www.pudge.wang:3080/api";

const http = {
  get(url, params) {
    // console.log(params);  {a:3,b:4} => ?a=3&b=4
    if (params) {
      const arr = Object.keys(params); // arr: ["a", "b"]
      const arr2 = arr.map((item) => item + "=" + params[item]); // ["a=3", "b=4"]
      url += "?" + arr2.join("&"); // "a=3&b=4"
    }

    return fetch(BASE_URL + url)
      .then((response) => response.json())
      .then((res) => {
        if (res.status === 0) {
          return res;
        }
      });
  },
  post(url, data) {
    NProgress.start();
    return fetch(BASE_URL + url, {
      method: "post",
      headers: {
        "content-type": "application/json",
      },
      body: JSON.stringify(data),
    })
      .then((response) => response.json())
      .then((res) => {
        NProgress.done();
        if (res.status === 0) {
          return res;
        }
      });
  },
};

export default http;
